package com.bwie.filter;

import com.bwie.utils.GatewayUtils;
import com.bwie.utils.JwtUtils;
import com.bwie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class AuthFilter implements Ordered, GlobalFilter {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final List<String> PATH=new ArrayList<String>(){{
       add("/auth/login");
       add("/system/user/findByUsername/**");
       add("/system/goods/upload");
    }};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        HttpMethod method = request.getMethod();
        if (StringUtils.matches(path,PATH)){
            return chain.filter(exchange);
        }
        //判断不能为空
        String token = request.getHeaders().getFirst(JwtUtils.TOKEN);
        if (token == null){
            return GatewayUtils.errorResponse(exchange,"token不能为空");
        }
        try {
            JwtUtils.parseToken(token);
        }catch (Exception e){
            e.printStackTrace();
        }
        //判断是否过期
        String userKey = JwtUtils.getUserKey(token);
        if (!redisTemplate.hasKey(JwtUtils.LOGIN_TOKEN_KEY+userKey)){
            return GatewayUtils.errorResponse(exchange,"token过期或为空");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
